//
//  AppDelegate+Extention.swift
//  KPBaseProject
//
//  Created by Kipp Dev on 2018/3/21.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import IQKeyboardManagerSwift
import GDPerformanceView_Swift
import MonkeyKing
import KafkaRefresh
import netfox
import RxAlamofire
import Alamofire
import Toast
import XHLaunchAd
import Onboard
//import AMapFoundationKit
import SKPhotoBrowser

extension AppDelegate {

    // MARK: - 创建视图
    func initWindow() {
        window = UIWindow(frame: Screen.bounds)


        window = UIWindow(frame: Screen.bounds)
        let tabbar = KPBaseTabbarViewController()
        window?.rootViewController = tabbar
        window?.makeKeyAndVisible()
        NotificationCenter.default.addObserver(self, selector: #selector(netChangeAction(noti:)), name: NSNotification.Name.reachabilityChanged, object: nil)
        reach?.startNotifier()
    }

    // MARK: - 创建键盘管理
    func IQKeyboardConfig() {
        let manager = IQKeyboardManager.sharedManager()
        manager.enable = true
        manager.shouldResignOnTouchOutside = true
    }

    // MARK: - 网络监听
    @objc
    func netChangeAction(noti: NotificationCenter) {
        ///配置超时
        Alamofire.SessionManager.default.session.configuration.timeoutIntervalForRequest = 20
        let internetStatus = reach?.currentReachabilityStatus()
        if let inter = internetStatus {
            switch inter {
            case .ReachableViaWiFi:
                applicationKeyWindow?.makeToast("切换至 WiFi 网络！")
            case .NotReachable:
                applicationKeyWindow?.makeToast("无网络，请检查网络是否畅通！")
            case .ReachableViaWWAN:
                applicationKeyWindow?.makeToast("切换至蜂窝移动网络！")
            }
        }

    }

    // MARK: - 性能查看
    func debugConfig() {
        #if DEBUG
        GDPerformanceMonitor.sharedInstance.startMonitoring()
        NFX.sharedInstance().start()
        #endif
    }

    // MARK: - 分享、支付配置
    func registeAccount() {
        MonkeyKing.registerAccount(.weChat(appID: Configs.WeChat.appID, appKey: Configs.WeChat.appKey, miniAppID: Configs.WeChat.miniAppID))
        MonkeyKing.registerAccount(.weibo(appID: Configs.Weibo.appID, appKey: Configs.Weibo.appKey, redirectURL: Configs.Weibo.redirectURL))
        MonkeyKing.registerAccount(.qq(appID: Configs.QQ.appID))
    }

    // MARK: - 全局下拉刷新配置
    func pullRefreshConfig() {
        KafkaRefreshDefaults.standard().headDefaultStyle = .native
        KafkaRefreshDefaults.standard().footDefaultStyle = .replicatorDot
    }

    // MARK: - 普通配置
    func config() {
        NetworkActivityIndicatorManager.shared.isEnabled = true
        CSToastManager.sharedStyle().titleFont = 15.mediumFont
        CSToastManager.sharedStyle().messageFont = 15.font
        CSToastManager.sharedStyle().displayShadow = true
        ///配置大图预览的网络图片缓存
        SKCache.sharedCache.imageCache = KPImageCache()
    }

    // MARK: - 广告页
    func advert() {
        //        XHLaunchAd.setLaunch(SourceType.launchImage)
        let advert = XHLaunchImageAdConfiguration()
        advert.duration = 5
        advert.frame = CGRect.init(x: 0, y: 0, width: Screen.width, height: Screen.height)
        advert.imageNameOrURLString = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523164620255&di=751cc9cc768ec931e469406cbc740f6a&imgtype=0&src=http%3A%2F%2Fclub1.autoimg.cn%2Falbum%2Fuserphotos%2F2015%2F05%2F31%2F12%2F400_54354410-5983-7mf9-454c-n204acck692h.jpg"
        advert.gifImageCycleOnce = false
        advert.contentMode = .scaleToFill
        advert.imageOption = .refreshCached
        advert.openModel = "http://www.it7090.com"
        advert.showFinishAnimate = .fadein
        advert.showFinishAnimateTime = 0.8
        advert.skipButtonType = .timeText
        advert.showEnterForeground = false
        XHLaunchAd.imageAd(with: advert, delegate: self)
    }
    ///
    // MARK: - 引导页
    func launch() {
        if Preferences[.firstLaunch] {
            //第一次启动
            Preferences[.firstLaunch] = false
            initLaunch()
        } else {
            //第1+次启动
            KPLog("第1+次启动")
            initWindow()
            //广告页
            //            advert()
        }

    }

    // 初始化启动页
    func initLaunch() {
        let firstPage = OnboardingContentViewController(title: "first page title", body: "first page body", image: UIImage(named: "07.jpg"), buttonText: "first text button") {
            // button action
        }

        let secondPage = OnboardingContentViewController(title: "second page title", body: "second page body", image: UIImage(named: "08.jpg"), buttonText: "second text button") {
            // button action
        }

        let thirdPage = OnboardingContentViewController(title: "third page title", body: "third page body", image: UIImage(named: "015.jpg"), buttonText: "third text button") {
            // button action
        }

        let fourthPage = OnboardingContentViewController(title: "fourth page title", body: "fourth page body", image: UIImage(named: "027.jpg"), buttonText: "fourth text button") {
            // button action
        }

        let onboardingVC = OnboardingViewController(backgroundImage: UIImage(named: "027.jpg"), contents: [firstPage, secondPage, thirdPage, fourthPage])
        onboardingVC?.allowSkipping = true
        self.window?.rootViewController = onboardingVC
        onboardingVC?.skipHandler = ({
            self.initWindow()
        })
    }
    func initMap() {
//        AMapServices.shared().apiKey = "613adac983bd4448e23a153665571ada"
    }
}

extension XHLaunchAdDelegate {
    func xhLaunchAd(_ launchAd: XHLaunchAd, clickAndOpenModel openModel: Any, click clickPoint: CGPoint) {
        KPLog("点击跳转web")
        //        if openModel == nil {
        //            return
        //        }else{
        //            let urlStr = openModel as! String
        //            //跳转广告页面
        //        }
    }
}

// MARK: - 自定义打印方法
func KPLog<T>(_ message: T, file: String = #file, funcName: String = #function, lineNum: Int = #line, color: UIColor? = nil) {

    #if DEBUG
    let fileName = (file as NSString).lastPathComponent
    print("\(fileName):(\(lineNum))-\(message)")
    #endif
}
